<template>
  <div>
    <el-upload :action="uploadUrl()" list-type="picture-card" accept=".jpg,.jpeg,.png,.gif" :data="data" multiple
      :headers="myHeaders" :file-list="fileList" :on-remove="handleRemove" :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload" :on-preview="handlePreview" :limit="maxCount" :on-exceed="handleExceed">
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" :alt="dialogImageName" />
    </el-dialog>
  </div>
</template>
<script>
import { baseURL, imageServer, tokenName, empIdName } from '@/config'
export default {
  name: 'UploadImage',
  props: {
    // 最大上传图片数量
    data: {
      default: {},
    },
    maxCount: {
      type: Number,
      default: 9,
    },
  },
  data() {
    return {
      fileList: [],
      imagesList: [],
      images: [],
      dialogVisible: false,
      dialogImageUrl: null,
      dialogImageName: '',
      num: 0,
      fileNum: 0,
      myHeaders: {},
    }
  },
  created() {
    this.myHeaders[tokenName] = this.$store.getters['user/accessToken']
    this.myHeaders[empIdName] = this.$store.getters['user/curEmp'].EMP_ID
    // 上传组件显示列表
    this.fileList = this.value
    // 图片保存数组
    this.imagesList = this.value
  },
  methods: {
    // 文件上传地址
    uploadUrl() {
      return imageServer + 'api/UserApi/File/UploadSurveyFile'
    },
    handleRemove(file, fileList) {
      const list = JSON.parse(JSON.stringify(fileList))
      this.imagesList = list.map((item) => ({
        name: item.name,
        url: item.url,
      }))
      this.$emit('input', this.imagesList)
    },
    handlePreview(file) {
      this.dialogVisible = true
      this.dialogImageUrl = file.url
      this.dialogImageName = file.name
    },
    handleUploadSuccess(res, file) {
      // console.log(res, file)
      if (res.code == 200) {
        this.$emit('uploadSuccess', res)
      }
    },
    handleBeforeUpload(file) {
      this.fileNum++
      console.log('上传个数：' + this.fileNum)
    },
    handleExceed(files, fileList) {
      this.$message({
        message: '最多只能上传' + this.maxCount + '张图片',
        type: 'warning',
        duration: 1000,
      })
    },
  },
}
</script>
<style scoped lang="scss"></style>
